package base_init

import (
	"github.com/gin-gonic/gin/binding"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	"go-likaladi-shop/common/base_global"
	validate "go-likaladi-shop/common/base_validate"
	"go.uber.org/zap"
)

func CustomValidate() {
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		//初始自定义电话格式校验
		customValidate("customMobile", "非法的手机号码!", validate.Mobile, v)
		//初始自定义email格式校验
		customValidate("customEmail", "不是合法的邮箱地址!", validate.Email, v)

		zap.S().Infof("注册自定义参数校验规则")
	}
}

func customValidate(customTag, errorMsg string, fn validator.Func, v *validator.Validate) {
	errorValidate := "注册自定义【" + customTag + "】校验器失败"
	errorLog := "注册自定义【" + customTag + "】校验翻译失败"

	if err := v.RegisterValidation(customTag, fn); err != nil {
		zap.S().Errorw(errorValidate, "errorMsg", err.Error())
		panic(errorValidate)
	}

	if err := v.RegisterTranslation(customTag, base_global.Trans, func(ut ut.Translator) error {
		return ut.Add(customTag, "{0} "+errorMsg, true)
	}, func(ut ut.Translator, fe validator.FieldError) string {
		t, _ := ut.T(customTag, fe.Field())
		return t
	}); err != nil {
		zap.S().Errorw(errorLog, "errorMsg", err.Error())
		panic(errorLog)
	}
}
